import { memo, useState, useEffect, useMemo } from 'react';
import { Collapse } from 'antd-mobile';
import Avatar from './Avatar';
import { InbizIcon } from '@inbiz/utils';
import { getProcessLog } from './service';
import { processState } from './utils';
import { TextWidget, getMessage } from '@inbiz/react';
import moment from 'moment';
import { useInbizRouter } from '@inbiz/hooks';
import './index.less';

const UserImg = (props: { userId: string }) => {
  return useMemo(() => {
    return props?.userId ? (
      <Avatar
        style={{ width: 32, height: 32, marginLeft: 19, marginRight: 15, borderRadius: 16 }}
        userId={props?.userId}
      />
    ) : (
      <InbizIcon
        type="icon-process-defaultAvatar"
        style={{ fontSize: 30, marginLeft: 19, marginRight: 15, borderRadius: 4 }}
      />
    );
  }, [props?.userId]);
};

const Log = memo((props: any) => {
  const { setProcessLogData, show } = props;
  const [logList, $logList] = useState<any>([]);
  const [activeKey, $activeKey] = useState<string[]>([]);
  const router = useInbizRouter();
  const _query = router.location.query;
  useEffect(() => {
    getProcessLog({ processInstanceId: _query.instanceId }).then((res) => {
      if (res && res.details && res.details.rows && res.details.rows.length > 0) {
        const logs: any[] = [];
        const keys: string[] = [];
        const mutationrows = [];
        const newRows = res.details.rows;
        setProcessLogData(res.details.rows);
        const i = newRows.length - 1;
        if (newRows[i].taskState != '170') {
          newRows[i].taskState = '220';
        }
        for (let index = 0; index < newRows.length; index++) {
          const element = newRows[index];
          // if (element.task_Def_id.includes(':')) {
          //   const arr = element.task_Def_id.split(':');
          //   element.task_Def_id = arr[1];
          // }
          mutationrows.push(element);
        }
        [...mutationrows, {}].reduce((total, current, currentIndex, array) => {
          if (array[total].task_Def_id != current.task_Def_id) {
            logs.push(array.slice(total, currentIndex));
            return currentIndex;
          } else {
            // if (currentIndex == array.length - 1) {
            //   a.push(array.slice(total))
            // }
            return total;
          }
        }, 0);
        $logList(logs);
        for (let index = 0; index < logs.length; index++) {
          keys.push(String(index));
        }
        $activeKey(keys);
      }
    });
  }, []);

  const getStateName = (item: any[]) => {
    let index = 0;
    if (item.findIndex((ele: { taskState: string; }) => ele.taskState == '170') > -1) {
      index = item.findIndex((ele: { taskState: string; }) => ele.taskState == '170');
    } else if (item.findIndex((ele: { taskState: string; }) => ele.taskState == '220') > -1) {
      index = item.findIndex((ele: { taskState: string; }) => ele.taskState == '220');
    } else if (item.findIndex((ele: { taskState: string; }) => ele.taskState == '10') > -1) {
      index = item.findIndex((ele: { taskState: string; }) => ele.taskState == '10');
    } else if (item.findIndex((ele: { taskState: string; }) => ele.taskState == '50') > -1) {
      index = item.findIndex((ele: { taskState: string; }) => ele.taskState == '50');
    } else if (item.findIndex((ele: { taskState: string; }) => ele.taskState == '130') > -1) {
      index = item.findIndex((ele: { taskState: string; }) => ele.taskState == '130');
    } else if (item.findIndex((ele: { taskState: string; }) => ele.taskState == '0') > -1) {
      index = item.findIndex((ele: { taskState: string; }) => ele.taskState == '0');
    } else if (item.findIndex((ele: { taskState: string; }) => ele.taskState == '5') > -1) {
      index = item.findIndex((ele: { taskState: string; }) => ele.taskState == '5');
    } else if (item.findIndex((ele: { taskState: string; }) => ele.taskState == '20') > -1) {
      index = item.findIndex((ele: { taskState: string; }) => ele.taskState == '20');
    }
    return index;
  };

  return (
    <div
      className={'processLog'}
      style={{ height: props?.hasButton ? `calc(100% - 493px)` : `calc(100% - 63px)`, display: show === false ? 'none' : 'block' }}
    >
      <Collapse activeKey={activeKey} onChange={(value) => $activeKey(value)}>
        {logList.map((item: any, index: number) => {
          return (
            <Collapse.Panel
              className={'logContainer'}
              key={String(index)}
              title={
                <header className={'logHeader'}>
                  {/** 用户任务 */}
                  <InbizIcon
                    type={
                      processState[item[getStateName(item)].taskState]
                        ? processState[item[getStateName(item)].taskState].secondName ==
                          'WapProcessLog.refuse'
                          ? 'icon-yiwancheng'
                          : processState[item[getStateName(item)].taskState].stateIcon
                        : 'icon-close_filled'
                    }
                    style={{ fontSize: 22, color: 'orange' }}
                  />
                  <span className={'userTask'}>{item[0].name}</span>
                  <span
                    className={'step'}
                    style={{
                      color: processState[item[getStateName(item)].taskState]
                        ? processState[item[getStateName(item)].taskState].secondName ==
                          'WapProcessLog.refuse'
                          ? '#71b771'
                          : processState[item[getStateName(item)].taskState].stateColor
                        : 'orange',
                    }}
                  >
                    <span
                      className={'dot'}
                      style={{
                        background: processState[item[0].taskState]
                          ? processState[item[getStateName(item)].taskState].secondName ==
                            'WapProcessLog.refuse'
                            ? '#71b771'
                            : processState[item[0].taskState].stateColor
                          : 'orange',
                      }}
                    />
                    {processState[item[getStateName(item)].taskState] ? (
                      processState[item[getStateName(item)].taskState].secondName ==
                        'WapProcessLog.refuse' ? (
                        <TextWidget>WapProcessLog.approved</TextWidget>
                      ) : (
                        <TextWidget>
                          {processState[item[getStateName(item)].taskState].secondName}
                        </TextWidget>
                      )
                    ) : (
                      item[getStateName(item)].taskState
                    )}
                    {/**缺多个人审批  每一项的审批状态接口 */}
                  </span>
                </header>
              }
              arrow={<InbizIcon type="icon-ic-show_more" />}
            >
              <section className={'logBody'}>
                {item.map((user: any, i: number) => (
                  <div key={i}>
                    <header className={'cardHeader'}>
                      {/** 审批人 操作类型 */}
                      <h4 style={{ display: 'flex', width: '40%' }}>
                        <UserImg userId={user.userIdentityID} />
                        <span className={'userName'} title={user.assigneeName}>
                          {user.assigneeName}
                        </span>
                      </h4>
                      {user.taskState != '0' ? (
                        <p>
                          {processState[user.taskState] ? (
                            user.taskState == '50' ? (
                              <TextWidget>WapProcessLog.beenassigned</TextWidget>
                            ) : user?.taskState == '150' &&
                              user?.task_Def_id?.indexOf('ctSign-') > -1 ? (
                              <TextWidget>WapProcessLog.plusSignComplete</TextWidget>
                            ) : (
                              (item?.length == 1 && user?.taskState == '1') ? <TextWidget>WapProcessLog.agree</TextWidget> :
                                (item?.some((item4: any) => item4?.taskState == '5') && user?.taskState != '5') ?
                                  <TextWidget>WapProcessLog.autom</TextWidget> :
                                  <TextWidget>{processState[user.taskState].stateName}</TextWidget>
                            )
                          ) : (
                            getMessage('WapProcessLog.noStatus')
                          )}
                          {user.taskState == '50' ? ' ' : ' · '}
                          {user.taskState == '50'
                            ? ''
                            : user.endTime
                              ? moment(user.endTime).format('YYYY/MM/DD HH:mm')
                              : processState[user?.taskState]?.secondName ==
                                'WapProcessLog.approvaling'
                                ? ''
                                : moment(user.startTime).format('YYYY/MM/DD HH:mm')}
                        </p>
                      ) : <p><TextWidget>WapProcessLog.approvaling</TextWidget></p>}
                    </header>
                    {/**摘要 */}
                    {user.comment && (
                      <section className={'cardBody'}>
                        <h5>
                          <TextWidget>WapProcessLog.comment</TextWidget>:
                        </h5>
                        <p className={'commentText'} title={user.comment}>
                          {user.comment}
                        </p>
                      </section>
                    )}
                    {/**拥有taskOwnerName assigneeName两个字段,代表指派*/}
                    {user.taskOwnerName && user.assigneeName && (
                      <header className={'cardHeader'}>
                        <h4 style={{ display: 'flex', width: '40%' }}>
                          <UserImg userId={user.ownUserID} />
                          <span className={'userName'} title={user.taskOwnerName}>
                            {' '}
                            {user.taskOwnerName}
                          </span>
                        </h4>
                        {user.taskState != '0' && (
                          <p style={{ fontSize: 12 }}>
                            {processState[user.taskState] ? (
                              <TextWidget>{processState['50'].stateName}</TextWidget>
                            ) : (
                              getMessage('WapProcessLog.noStatus')
                            )}
                            {user.taskState == '50' ? ' ' : ': '}
                            {user.taskState == '50'
                              ? ''
                              : user.endTime
                                ? moment(user.endTime).format('YYYY/MM/DD HH:mm')
                                : processState[user?.taskState]?.secondName ==
                                  'WapProcessLog.approvaling'
                                  ? ''
                                  : moment(user.startTime).format('YYYY/MM/DD HH:mm')}
                          </p>
                        )}
                      </header>
                    )}
                    {/**taskOwnerName 指派给 assigneeName */}
                    {user.taskOwnerName && user.assigneeName && (
                      <section className={'cardBody'}>
                        <p className={'commentText'} title={user.comment}>
                          {user.taskOwnerName} <TextWidget>WapProcessLog.assignto</TextWidget>{' '}
                          {user.assigneeName}
                        </p>
                      </section>
                    )}
                    {/** 抄送 */}
                    {user.ccMember && (
                      <section className={'cardBody'}>
                        <h5>
                          <TextWidget>WapProcessLog.ccMember</TextWidget>:
                        </h5>
                        <p className={'commentText'} title={user.ccMember}>
                          {user.ccMember}
                        </p>
                      </section>
                    )}
                  </div>
                ))}
              </section>
            </Collapse.Panel>
          );
        })}
      </Collapse>
    </div>
  );
});

export default Log;
